package controllers

import auth.AuthActionWrapper
import dao._
import implicits.Implicits._
import models.Tables._
import org.joda.time.DateTime
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.Tool
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import shared.pojo.Pojo._
import ujson.play.PlayJson
import upickle.default._
import auth.AuthTool._

/**
 * Created by Administrator on 2019/8/7
 */
class WechatMemberController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val wechatMemberDao: WechatMemberDao,
  implicit val authAction: AuthActionWrapper,
) extends
  AbstractController(cc) {

  import wechatMember._

  def add = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[Add.Request])
    val row = WechatMemberRow(phone = data.phone, createTime = new DateTime(), password = data.password.hashedPassword)
    wechatMemberDao.insert(row).map { x =>
      val response = ValidData(valid = true)
      Ok(writeJs(response))
    }
  }

  def all = adminAuth.async { implicit request =>
    wechatMemberDao.selectAll.map { x =>
      val array = x.map(x => writeJs(x))
      Ok(writeJs(array))
    }
  }

  def delete = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[PhoneData])
    wechatMemberDao.deleteByPhone(data.phone).map { x =>
      val response = ValidData(valid = true)
      Ok(writeJs(response))
    }
  }

  def phoneCheck = Action.async { implicit request =>
    val data = Tool.transformRq.transform(reader[PhoneData])
    val bsF = Future.sequence(
      List(
        wechatMemberDao.phoneExist(data.phone)
      )
    )
    bsF.zip(accountDao.selectById1).map { case (bs, admin) =>
      val response = if (bs.exists(x => x)) {
        ValidData(valid = false)
      } else {
        ValidData(valid = true)
      }
      Ok(writeJs(response))
    }
  }

  def update = adminAuth.async { implicit request =>
    val data = PlayJson.transform(request.body.asJson.get, reader[WechatMemberData])
    wechatMemberDao.select(data.phone).flatMap { dbUser =>
      val row = dbUser.copy(password = data.password.hashedPassword)
      wechatMemberDao.update(row).map { x =>
        val response = ValidData(valid = true)
        Ok(writeJs(response))
      }
    }
  }

  def getByPhone = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[PhoneData])
    wechatMemberDao.select(data.phone).map { x =>
      Ok(writeJs(x))
    }
  }


}
